package com.ruoyi.common.utils;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.ruoyi.common.utils.sign.Base64;
import com.ruoyi.common.utils.spring.SpringUtils;
import org.springframework.core.env.Environment;

import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Hashtable;
import java.util.Map;
import java.util.Objects;

/**
 * @author : hcl
 * @Date : 2023/8/16 10:28
 */
public class QrCodeUtils extends QrCodeUtil {
    /**
     * @param teamId 项目id
     * @param wayId  联系我id
     */
    public static String contactWayQrcode(Long teamId, Long wayId) {
        Environment ev = SpringUtils.getBean(Environment.class);
        if (Objects.nonNull(ev)) {
            String domain = ev.getProperty("server.domain");
            StringBuilder way = new StringBuilder("/wxqy/mobile/friend/qrcode/");
            way.append(teamId).append("/").append(wayId);
            Base64.encode(way.toString().getBytes(StandardCharsets.UTF_8));
        }
        return "";
    }

    /**
     * 生成二维码
     * David
     *
     * @param url     url 网址
     * @param width   二维码宽度
     * @param height  二维码高度
     * @param imgPath 生成的二维码url: 路径+文件名
     */
    public static void encode(String url, int width, int height, String imgPath) {
        Map<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        // 指定纠错等级
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        // 指定编码格式
        hints.put(EncodeHintType.CHARACTER_SET, "UTF8");
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, width, height, hints);
            MatrixToImageWriter.writeToStream(bitMatrix, "png", new FileOutputStream(imgPath));
//            MatrixToImageWriter.writeToStream(bitMatrix, "png", response.getOutputStream());// 输出图像
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        QrConfig qrConfig = QrConfig.create().setWidth(512)
                .setHeight(512);
//        BufferedImage image = generate("/sss/wwe/234", 512, 512);
        String encode = Base64.encode("/sss/wwe/234".getBytes(StandardCharsets.UTF_8));
        System.out.println(encode);
        System.out.println(new String(Base64.decode(encode),StandardCharsets.UTF_8));

    }
}
